package com.evaluation.kexingcp.psycho.evaluation.sys.evaluation

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.evaluation.kexingcp.admin.service.SysTenantService
import com.evaluation.kexingcp.admin.service.SysUserService
import com.evaluation.kexingcp.common.core.util.R
import com.evaluation.kexingcp.common.data.tenant.TenantContextHolder
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationWarningFollowEntity
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationTaskService
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationWarningFollowService
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationWarningRecordsService
import com.evaluation.kexingcp.psycho.evaluation.sys.utils.transpose
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/indexPage")
class IndexPageController(
    private val evaluationTaskService: EvaluationTaskService,
    private val sysTenantService: SysTenantService,
    private val evaluationWarningRecordsService: EvaluationWarningRecordsService,
    private val evaluationWarningFollowService: EvaluationWarningFollowService,
    private val userService: SysUserService,
) {

    @GetMapping("/usersStatus")
    fun usersStatus(): R<Any> {
        val res = mutableListOf<Map<String, Any>>()
        val users = evaluationTaskService.userDeptStatus()
        res.add(mapOf("title" to "用户总数", "classData" to "orange", "icon" to "icon-zongrenshu", "total" to users.size))
        res.add(mapOf("title" to "男性人数", "classData" to "blue", "icon" to "icon-nansheng", "total" to users.filter { it.sex == "男" }.size))
        res.add(mapOf("title" to "女性人数", "classData" to "pink", "icon" to "icon-nvsheng", "total" to users.filter { it.sex == "女" }.size))
        res.add(mapOf("title" to "预警人数", "classData" to "red", "icon" to "icon-yujing", "total" to evaluationWarningFollowService.count(QueryWrapper<EvaluationWarningFollowEntity>().isNull("pid").eq("completed", "0"))))
        res.add(mapOf("title" to "解除预警人数", "classData" to "green", "icon" to "icon-yijiechuyujing", "total" to evaluationWarningFollowService.count(QueryWrapper<EvaluationWarningFollowEntity>().isNull("pid").eq("completed", "1"))))
        res.add(mapOf("title" to "咨询师人数", "classData" to "yellow", "icon" to "icon-a-xinlijiankangzixunshi", "total" to userService.listUserIdByRoleName("TEACHER").size))

        return R.ok(res)
    }


    data class UserDeptNum(
        val name: String?,
        var value: Int
    )


    @GetMapping("/usersByDept")
    fun usersByDept(): R<Any> {
        val users = evaluationTaskService.userWarningByDept()
        val tenant = sysTenantService.getById(TenantContextHolder.getTenantId())
        val data = mutableListOf<UserDeptNum>()
        users
            .groupingBy {
            when (tenant.orgType) {
                "中小学" -> {
                    it.parentDeptName
                }
                else -> it.deptName
            }
        }
            .aggregate { key, acc: String?, _, first ->
                if (first) {
                    data.add(UserDeptNum(key, 1))
                } else {
                    data.first { it.name == key }.value += 1
                }

                acc
            }
        return R.ok(data)
    }


    data class AreaLegendData(
        val area: MutableList<String?> = mutableListOf(),
        val legend: List<String> = listOf("男", "女"),
        var data: MutableList<MutableList<Int>> = mutableListOf(),
    )

    @GetMapping("/sexUsersByDept")
    fun sexUsersByDept(): R<Any> {
        val users = evaluationTaskService.userWarningByDept()
        val tenant = sysTenantService.getById(TenantContextHolder.getTenantId())
        val acc = AreaLegendData()
        users.groupingBy {
            when (tenant.orgType) {
                "中小学" -> {
                    it.parentDeptName
                }
                else -> it.deptName
            }

        }.aggregate { key, _: AreaLegendData?, element, first ->
            if (first) {
                acc.area.add(key)
                acc.data.add(MutableList(2) { 0 })
            }

            // 通过area找到部门的index
            val index = acc.area.indexOf(key)

            when (element.sex) {
                "男" -> {
                    acc.data[index][0] = acc.data[index][0].plus(1)
                }
                "女" -> {
                    acc.data[index][1] = acc.data[index][1].plus(1)
                }
            }

            acc
        }

        acc.data = transpose(acc.data)
        return R.ok(acc)
    }

    // 正常,再婚,单亲,离异
    @GetMapping("/parentMarriageByDept")
    fun parentMarriageByDept(): R<Any> {
        val users = evaluationTaskService.userDeptStatus()
        val tenant = sysTenantService.getById(TenantContextHolder.getTenantId())
        val acc = AreaLegendData(legend = listOf("正常","再婚","单亲","离异"))
        users.groupingBy {
            when (tenant.orgType) {
                "中小学" -> {
                    it.parentDeptName
                }
                else -> it.deptName
            }

        }.aggregate { key, _: AreaLegendData?, element, first ->
            if (first) {
                acc.area.add(key)
                acc.data.add(MutableList(4) { 0 })
            }

            // 通过area找到部门的index
            val index = acc.area.indexOf(key)

            when (element.parentMarriage) {
                "正常" -> {
                    acc.data[index][0] = acc.data[index][0].plus(1)
                }
                "再婚" -> {
                    acc.data[index][1] = acc.data[index][1].plus(1)
                }
                "单亲" -> {
                    acc.data[index][2] = acc.data[index][2].plus(1)
                }
                "离异" -> {
                    acc.data[index][3] = acc.data[index][3].plus(1)
                }
            }

            acc
        }

        acc.data = transpose(acc.data)
        return R.ok(acc)
    }

    // 陪伴情况: 父母一方陪伴,留守儿童,父母双方陪伴
    @GetMapping("/partnerStatusByDept")
    fun partnerStatusByDept(): R<Any> {
        val users = evaluationTaskService.userDeptStatus()
        val tenant = sysTenantService.getById(TenantContextHolder.getTenantId())
        val acc = AreaLegendData(legend = listOf("父母一方陪伴","留守儿童","父母双方陪伴"))
        users.groupingBy {
            when (tenant.orgType) {
                "中小学" -> {
                    it.parentDeptName
                }
                else -> it.deptName
            }

        }.aggregate { key, _: AreaLegendData?, element, first ->
            if (first) {
                acc.area.add(key)
                acc.data.add(MutableList(3) { 0 })
            }

            // 通过area找到部门的index
            val index = acc.area.indexOf(key)

            when (element.partnerStatus) {
                "父母一方陪伴" -> {
                    acc.data[index][0] = acc.data[index][0].plus(1)
                }
                "留守儿童" -> {
                    acc.data[index][1] = acc.data[index][1].plus(1)
                }
                "父母双方陪伴" -> {
                    acc.data[index][2] = acc.data[index][2].plus(1)
                }
            }

            acc
        }

        acc.data = transpose(acc.data)
        return R.ok(acc)
    }

    // 婚姻情况(未婚、已婚、丧偶、再婚)
    @GetMapping("/marriageStatusByDept")
    fun marriageStatusByDept(): R<Any> {
        val users = evaluationTaskService.userDeptStatus()
        val tenant = sysTenantService.getById(TenantContextHolder.getTenantId())
        val acc = AreaLegendData(legend = listOf("未婚","已婚","丧偶","再婚"))
        users.groupingBy {
            when (tenant.orgType) {
                "中小学" -> {
                    it.parentDeptName
                }
                else -> it.deptName
            }

        }.aggregate { key, _: AreaLegendData?, element, first ->
            if (first) {
                acc.area.add(key)
                acc.data.add(MutableList(4) { 0 })
            }

            // 通过area找到部门的index
            val index = acc.area.indexOf(key)

            when (element.marriage) {
                "未婚" -> {
                    acc.data[index][0] = acc.data[index][0].plus(1)
                }
                "已婚" -> {
                    acc.data[index][1] = acc.data[index][1].plus(1)
                }
                "丧偶" -> {
                    acc.data[index][2] = acc.data[index][2].plus(1)
                }
                "再婚" -> {
                    acc.data[index][3] = acc.data[index][3].plus(1)
                }
            }

            acc
        }

        acc.data = transpose(acc.data)
        return R.ok(acc)
    }

    @GetMapping("/oneChildByDept")
    fun oneChildByDept(): R<Any> {
        val users = evaluationTaskService.userDeptStatus()
        val tenant = sysTenantService.getById(TenantContextHolder.getTenantId())
        val acc = AreaLegendData(legend = listOf("是", "否"))
        users.groupingBy {
            when (tenant.orgType) {
                "中小学" -> {
                    it.parentDeptName
                }
                else -> it.deptName
            }

        }.aggregate { key, _: AreaLegendData?, element, first ->
            if (first) {
                acc.area.add(key)
                acc.data.add(MutableList(2) { 0 })
            }

            // 通过area找到部门的index
            val index = acc.area.indexOf(key)

            when (element.oneChild) {
                "是" -> {
                    acc.data[index][0] = acc.data[index][0].plus(1)
                }
                "否" -> {
                    acc.data[index][1] = acc.data[index][1].plus(1)
                }
            }

            acc
        }

        acc.data = transpose(acc.data)
        return R.ok(acc)
    }


}